# -*- coding: utf8 -*-

import sys, os
if sys.platform != 'linux2':
    print 'eggrevenger is tested with linux 2.x only'
    # exit(1)
import getopt
# переходим в директорию где лежит main.py
# там же скорее всего можно найти и остальные файлы бота
coredir = os.path.dirname(sys.argv[0])
if coredir == '': coredir = '.'
os.chdir(coredir)

from core import __version__
config_file = "./eggrevenger.conf"

def usage():
    print "Usage:"
    print " %s -c /path/to/eggrevenger.conf" % sys.argv[0]
    print " %s -v" % sys.argv[0]
    print " %s -h" % sys.argv[0]

try:
    opts, args = getopt.getopt(sys.argv[1:], "hc:v", ["help", "config=", "version"])
except getopt.GetoptError, err:
    print str(err)
    usage()
    sys.exit(2)
for o, a in opts:
    if o in ("-v", "--version"):
        print "eggrevenger %s" % __version__
        sys.exit()
    elif o in ("-h", "--help"):
        usage()
        sys.exit()
    elif o in ("-c", "--config"):
        config_file = a
    else:
        assert False, "unhandled option"

from twisted.internet import reactor
from twisted.python.log import startLogging
from core.bot import eggrevenger
from core import config

config.load(config_file)
sys.path.insert(0, config.core_dir)

startLogging(config.logfile)

bot = eggrevenger(config, reactor)

if config.ssl:
    from twisted.internet.ssl import ClientContextFactory
    reactor.connectSSL(config.host, config.port, bot, ClientContextFactory())
else:
    reactor.connectTCP(config.host, config.port, bot)

reactor.run()

config.logfile.close()
